<template>
  <div
    class="common-layout"
    v-if="$store.state.isCompleted"
    v-loading.fullscreen.lock="fullscreenLoading"
  >
    <el-header>
      <audio
        v-show="true"
        id="audio"
        ref="audio"
        src="@/assets/baojing.mp3"
        loop
      />
      <div class="home-title">
        <b>{{ projectTitle }}</b>
      </div>
      <div class="leftTabs" :style="{ marginTop: menuStyle ? '0px' : '0px' }">
        <el-tabs
          class="tabs1"
          v-model="mainMenuId"
          @tab-click="handleClickMainMenu"
          :stretch="true"
        >
          <el-tab-pane
            class="item"
            :name="item.id"
            v-for="(item, id) in menu"
            :key="id"
          >
            <slot slot="label">
              <dv-border-box-7 :color="['#0595eb']">
                <div class="itemlist">{{ item.name }}</div>
              </dv-border-box-7>
            </slot>
            <el-tabs
              class="tabs2"
              v-model="subMenuId"
              @tab-click="handleClickSubMenu"
            >
              <el-tab-pane
                :label="item2.name"
                :name="item2.id"
                v-for="(item2, id2) in item.childMenu"
                :key="id2"
              >
              </el-tab-pane>
            </el-tabs>
            <div class="childMenuBg" v-if="!menuStyle"></div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="home-tools">
        <el-badge
          :value="TableList.length"
          :max="99"
          :hidden="TableList.length < 1"
          class="item"
        >
          <i
            class="iconfont icon-tixing icon-item"
            @click="tixingDialogVisible = true"
            :class="{ rotate: istixing }"
          ></i>
        </el-badge>
        <div>
          <img
            @click="handleFullScreen"
            v-if="isFullscreen"
            title="退出全屏"
            src="../../assets/img/home/escquanping.png"
            alt=""
          /><img
            @click="handleFullScreen"
            v-else
            title="全屏"
            src="../../assets/img/home/quanping.png"
            alt=""
          />
        </div>
        <div>
          <img
            title="退出登录"
            @click="logout"
            src="../../assets/img/home/tuichu.png"
            alt=""
          />
        </div>
      </div>
    </el-header>
    <el-main style="padding: 0px">
      <!-- <router-view> -->
      <div class="layout" v-if="showViewer">
        <div :style="bigScreenStyle" style="">
          <widget
            v-for="(widget, index) in widgets"
            :key="widgetKey + index"
            v-model="widget.value"
            :type="widget.type"
            :pageId="id"
            :widgetIndex="index"
          />
        </div>
      </div>
      <!-- </router-view> -->
    </el-main>

    <!-- </el-container> -->
    <el-dialog
      :visible.sync="tixingDialogVisible"
      width="60%"
      :close-on-click-modal="false"
      custom-class="myClass"
      @close="CloseDrawer"
    >
      <ux-grid
        class="tableListValue"
        :key="random"
        :data="TableList"
        :widthResize="true"
        ref="plxTable1"
        stripe
        :border="false"
        :max-height="600"
        size="mini"
        :header-cell-style="{ 'text-align': 'center' }"
        style="width: 100%; font-size: 12px; margin: 0px 0px"
        :highlight-current-row="true"
        show-overflow="tooltip"
        widthResize
      >
        <ux-table-column
          v-for="(item, index) in columns"
          :key="index"
          :title="item.label"
          :field="item.prop"
          :align="item.align"
          :width="item.width"
          :formatter="item.formatter"
          resizable
        >
        </ux-table-column>
        <ux-table-column field="alarm_level" title="告警级别" width="150">
          <template slot-scope="scope">
            <el-tag
              v-if="TagschangeMessage(scope.row.alarm_level)"
              :type="TagsColorMessage(scope.row.alarm_level)"
              disable-transitions
              effect="dark"
              size="mini"
              >{{ TagschangeMessage(scope.row.alarm_level) }}</el-tag
            >
          </template>
        </ux-table-column>
      </ux-grid>
    </el-dialog>
  </div>
</template>

<script>
import widget from "../bigscreenDesigner/designer/widget/temp";
import { SCADA_MSG } from "@/mqtt/msg.js";
import screenfull from "screenfull";
import {
  setMessageCallback,
  removeMessageCallback,
  publishMsg,
  checkSpecialId,
} from "@/mqtt";
import store from "@/store/index.js";
export default {
  components: {
    widget,
  },
  //此处存放数据
  data() {
    return {
      projectTitle: "",
      menu: [],
      pageConfig: {},
      currentPageId: "",
      fullscreenLoading: false,
      istixing: false,
      mainMenuId: "",
      subMenuId: "",
      bigScreenStyle: {},
      widgets: [],
      dataList: {},
      timer: null,
      id: "",
      showViewer: true,
      drawer: false, //抽屉
      tixingDialogVisible: false, //警铃弹窗
      menuStyle: false,
      isFullscreen: false,
      TableList: [],
      columns: [
        {
          prop: "update_time",
          label: "告警时间",
          align: "left",
          width: "160",
        },
        {
          prop: "alarm_type",
          label: "告警类型",
          width: "100",
          formatter(row) {
            let rowkey = row.row;
            if (rowkey.hasOwnProperty("alarm_type")) {
              if (rowkey.alarm_type === 1) {
                return "遥信变位";
              }
              if (rowkey.alarm_type === 2) {
                return "遥测越限";
              }
              if (rowkey.alarm_type === 3) {
                return "网关事件";
              }
              if (rowkey.alarm_type === 4) {
                return "终端事件";
              }
              if (rowkey.alarm_type === 5) {
                return "遥控事件";
              }
              if (rowkey.alarm_type === 6) {
                return "遥调事件";
              }
            } else {
              return "";
            }
          },
        },
        // {
        //   prop: "id",
        //   label: "数据id",
        //   width: "200",
        // },
        // {
        //   prop: "name",
        //   label: "告警信息",
        // },
        // {
        //   prop: "desc",
        //   label: "数据描述",
        // },

        {
          prop: "alarm_desc",
          label: "告警描述",
        },
        {
          prop: "value",
          label: "值",
          width: "70",
        },
        {
          prop: "unit",
          label: "单位",
          width: "50",
        },
      ],
      random: 1,
      widgetKey: 0,
      audioNum: 0,
      isaudio: false,
    };
  },
  //计算属性
  //监听data中数据变化
  watch: {},
  created() {
    this.fullscreenLoading = true;
    console.log("chushihua ");
    this.initWidgetKey();
    //防止点击返回
    history.pushState(null, null, document.URL);
    window.addEventListener("popstate", function () {
      history.pushState(null, null, document.URL);
    });
  },
  mounted() {
    setMessageCallback(this.onMessage);
    if (screenfull.isEnabled) {
      screenfull.on("change", this.onFullScreenChange);
    }

    // 请求全部一次图
    let msg = {
      webMsgType: SCADA_MSG.scada_param_graph,
      funCode: 0,
      fullData: false,
    };

    publishMsg(msg);

    // 请求标题
    msg = { webMsgType: SCADA_MSG.scada_param_system, funCode: 0 };
    publishMsg(msg);

    // 请求菜单
    msg = {
      webMsgType: SCADA_MSG.scada_param_dashboard,
      funCode: 0,
    };
    publishMsg(msg);

    // this.handleFullScreen();
  }, //生命周期 - 挂载完成
  //方法集合
  methods: {
    TagschangeMessage(state) {
      var stateMap = {
        0: "无",
        1: "通知",
        2: "一般",
        3: "严重",
      };
      return stateMap[state] || "";
    },
    TagsColorMessage(state) {
      var stateMap = {
        0: "info",
        1: "success",
        2: "warning",
        3: "danger",
      };
      return stateMap[state] || "";
    },
    playaudio() {
      // var audio = document.getElementById("audio");
      this.$refs.audio.play(); //播放一段音频
      //audio.pause()  //暂停一段音频
    },
    playaudioStop() {
      // var audio = document.getElementById("audio");
      this.$refs.audio.pause(); //播放一段音频
      //audio.pause()  //暂停一段音频
    },
    initWidgetKey() {
      this.widgetKey = 8000 + Math.trunc(Math.random() * 8000);
    },
    refresh() {
      this.random = new Date().getTime() * 1000 + (this.random++ % 1000);
    },
    logout() {
      this.$confirm("您确定要退出登录吗, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let newMsg = {
            webMsgType: 1004,
            funCode: 0,
          };
          publishMsg(newMsg);
        })
        .catch(() => {});
    },
    saveWidgetsConfig() {
      if (!this.widgets || this.widgets.length == 0) {
        this.$message.error("请添加组件");
        return;
      }
      const pageConfigData = {
        dashboard: {
          title: this.dashboard.title,
          width: this.dashboard.width,
          height: this.dashboard.height,
          backgroundColor: this.dashboard.backgroundColor,
          backgroundImage: this.dashboard.backgroundImage,
        },
        widgets: this.widgets,
      };

      let newMsg = {
        webMsgType: 1022,
        funCode: 5,
        data: { id: this.$route.query.id, pageConfig: pageConfigData },
      };
      //console.log(newMsg);
      publishMsg(newMsg);
    },
    onFullScreenChange() {
      this.isFullscreen = screenfull.isFullscreen;
    },
    CloseDrawer() {
      this.refresh();
      this.TableList = [];
      this.istixing = false;
    },
    //全屏按钮展示
    handleFullScreen() {
      screenfull.toggle();
    },
    getDefaultPageId() {
      let currentId = "";
      if (this.menu.length > 0) {
        this.menuStyle = false; //动态绑定菜单样式
        this.mainMenuId = this.menu[0].id;
        currentId = this.mainMenuId;

        if (this.menu[0].childMenu.length > 0) {
          this.menuStyle = true; //动态绑定菜单样式
          this.subMenuId = this.menu[0].childMenu[0].id;
          currentId = this.subMenuId;
        }
      }

      if (currentId != this.currentPageId) {
        this.currentPageId = currentId;
      }
    },
    reqPageConfig() {
      // 请求菜单，
      // console.log("请求页面，id=", this.currentPageId);
      let msg = {
        webMsgType: SCADA_MSG.scada_param_dashboard,
        funCode: 4,
        data: {
          id: this.currentPageId,
        },
      };
      publishMsg(msg);

      // console.log(msg);
    },
    handleClickMainMenu(tab, event) {
      this.showViewer = false;
      let currentId = "";
      if (this.menu[Number(tab.index)].childMenu.length > 0) {
        this.menuStyle = true;
        this.subMenuId = this.menu[Number(tab.index)].childMenu[0].id;
        currentId = this.subMenuId;
      } else {
        this.menuStyle = false;
        this.subMenuId = "";
        currentId = this.mainMenuId;
      }
      if (currentId != this.currentPageId) {
        this.currentPageId = currentId;
        this.reqPageConfig();
        // console.log("点击主菜单");
      } else {
        this.showViewer = true;
      }
    },

    handleClickSubMenu(tab) {
      this.showViewer = false;
      if (this.subMenuId != this.currentPageId) {
        this.currentPageId = this.subMenuId;
        this.reqPageConfig();
        // console.log("点击子菜单");
      } else {
        this.showViewer = true;
      }
    },

    showView(data) {
      const equipment = document.body.clientWidth;
      const ratioEquipment = equipment / data.dashboard.width;
      this.bigScreenStyle = {
        width: data.dashboard.width + "px",
        height: data.dashboard.height + "px",
        // width: "100%",
        // height: "100%",
        "background-color": data.dashboard.backgroundColor + "!important",
        "background-image": "url(" + data.dashboard.backgroundImage + ")",
        "background-position": "0% 0%",
        "background-size": "100% 100%",
        "background-repeat": "initial",
        "background-attachment": "initial",
        "background-origin": "initial",
        "background-clip": "initial",
        // transform: `scale(${ratioEquipment}, ${ratioEquipment})`,
        // "transform-origin": "0 0",
      };

      this.widgets = [];
      this.initWidgetKey();
      this.widgets = data.widgets;
      this.showViewer = true;
    },

    onMessage(topic, msg) {
      let webMsgType = msg.webMsgType;
      let funCode = msg.funCode;
      switch (webMsgType) {
        case SCADA_MSG.scada_param_graph:
          {
            if (funCode == 0) {
              store.commit("initData", msg);
            }
          }
          break;
        case SCADA_MSG.scada_param_system:
          {
            if (funCode == 0) {
              let size = msg.data.length;
              for (let i = 0; i < size; i++) {
                if (msg.data[i].id == "project_title") {
                  this.projectTitle = msg.data[i].value;
                }
              }
            }
          }
          break;
        case SCADA_MSG.scada_param_dashboard:
          {
            switch (funCode) {
              case 0:
                {
                  if (checkSpecialId(msg)) {
                    let data = msg.data;
                    const size = data.length;
                    this.menu = [];
                    for (let i = 0; i < size; i++) {
                      if (data[i].type == 0) {
                        // 父菜单
                        data[i]["childMenu"] = [];
                        this.menu.push(data[i]);
                      } else {
                        // 子菜单
                        let parentId = data[i].parentId;
                        for (let j = 0; j < this.menu.length; j++) {
                          if (this.menu[j].id == parentId) {
                            this.menu[j]["childMenu"].push(data[i]);
                          }
                        }
                      }
                    }

                    this.getDefaultPageId();
                    this.reqPageConfig();
                    this.fullscreenLoading = false;
                  }
                }
                break;
              case 4:
                {
                  if (checkSpecialId(msg)) {
                    if (msg.retCode != 0) {
                      this.$message.error(msg.retMsg);
                    } else {
                      if (msg.data.id == this.currentPageId) {
                        const data = msg.data.pageConfig;
                        this.showView(data);
                      }
                    }
                  }
                }
                break;
              case 5:
                if (checkSpecialId(msg)) {
                  if (msg.retCode != 0) {
                    return this.$message.error(msg.retMsg);
                  } else {
                    this.$message.success("保存配置成功");
                  }
                }
                break;
              default:
                break;
            }
          }
          break;
        case SCADA_MSG.scada_param_alarm:
          {
            switch (funCode) {
              case 0:
                {
                  this.playaudioStop();
                  let alarm = false;
                  if (msg.data) {
                    msg.data.forEach((e) => {
                      if (e.alarm_voice == true) {
                        alarm = true;
                      }
                    });
                  }

                  if (alarm) {
                    this.playaudio();
                  }
                }
                break;
              case 2:
                {
                  if (msg.retCode != 0 || !msg.data) {
                    return this.$message.error(msg.retMsg);
                  }
                  if (msg.data) {
                    this.tixingDialogVisible = true;
                    this.refresh();
                    if (this.TableList.length > 99) {
                      this.TableList.pop();
                    }
                    this.TableList.unshift(msg.data);
                    this.istixing = true;
                  }
                }
                break;
              default:
                break;
            }
          }
          break;
        case SCADA_MSG.scada_logout:
          {
            switch (funCode) {
              case 0:
                {
                  if (checkSpecialId(msg)) {
                    if (msg.retCode != 0) {
                      return this.$message.error(msg.retMsg);
                    } else {
                      this.$router.push("/Login");
                      this.$message.success("您已退出登录！");
                    }
                  }
                }
                break;
              default:
                break;
            }
          }
          break;
        default:
          break;
      }
    },
  },
  destroyed() {
    if (this.timer != null) {
      clearTimeout(this.timer);
      this.timer = null;
    }
    removeMessageCallback(this.onMessage);
    screenfull.off("change", this.onFullScreenChange);
  },
};
</script>
<style lang="scss" scoped>
::v-deep.el-tag--dark.el-tag--danger {
  background-color: red;
  border-color: red;
  color: #fff;
}

::v-deep .el-tag--dark.el-tag--danger {
  background-color: red;
  border-color: red;
  color: #fff;
}

::v-deep .el-tag--dark.el-tag--warning {
  background-color: yellow;
  border-color: yellow;
  color: red;
}

::v-deep .el-tag--dark.el-tag--success {
  background-color: green;
  border-color: green;
  color: #fff;
}

@import "../../views/bigscreenDesigner/designer/widget/table/css/index.scss";

//展示区域样式
.layout {
  width: 100%;
  height: 100%;
  text-align: center;
  position: relative;
}

//导航菜单样式
.common-layout {
  width: 100%;
  min-height: 100%;
  background-color: #030409;
  // background-color: #fff;
  color: #fff;
  background-image: url(../../assets/img/bg.png);
  background-size: 100% 100%;
  background-size: cover;

  .home-box {
  }
}

.el-header {
  height: 90px !important;
  display: flex;
  align-items: center;
  justify-content: space-between;
  --el-header-padding: 0px;
  position: relative;
  padding: 0px 0px;
  margin: 0 10px 0 0;

  .home-title {
    display: flex;
    width: 500px;
    height: 100%;
    justify-content: center;
    align-items: center;
    font-size: 34px;

    b {
      margin-top: -17px;
      color: rgb(0, 232, 255);
    }
  }

  .home-tools {
    // position: absolute;
    display: flex;
    height: 100%;
    align-items: center;

    // justify-content: flex-end;
    div {
      cursor: pointer;
      margin: 0px 10px;

      img {
        width: 35px;
        height: 35px;
      }
    }

    i {
      cursor: pointer;
      font-size: 28px;
      color: rgba($color: #1296db, $alpha: 1);
    }
  }

  .leftTabs {
    // flex: 1;
    // margin: 60px 20px 0px 20px;
    width: 100%;
    height: 100%;

    ::v-deep .el-tabs__item {
      color: #fff;
      margin: 0 10px;
      padding: 0px;
      box-shadow: none !important;
    }

    ::v-deep
      .tabs1
      .el-tabs__nav-scroll
      .el-tabs__nav
      .el-tabs__item
      .itemlist {
      // width: 100px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      color: #fff;
      font-size: 16px;
      background-color: rgba(64, 160, 255, 0.202);
    }

    ::v-deep .tabs2 .el-tabs__nav-scroll .el-tabs__nav .el-tabs__item {
      width: 100px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      color: #fff;
      background-color: rgba(64, 160, 255, 0.202);
      // border-radius: 30px;
      margin: 0 10px;
      padding: 0px;
      box-shadow: none !important;
      background-image: url(../../assets/img/home/border_bg01.png);
      background-repeat: no-repeat;
      background-size: 100% 100%;
    }

    /*去掉tabs底部的下划线*/
    ::v-deep .el-tabs__nav-wrap::after {
      position: static !important;
    }

    ::v-deep .el-tabs__active-bar {
      background-color: transparent !important;
    }

    ::v-deep .el-tabs__header {
      margin-bottom: 10px;
    }

    ::v-deep
      .tabs1
      .el-tabs__nav-scroll
      .el-tabs__nav
      .el-tabs__item.is-active
      .itemlist {
      color: #3184d7;
      font-size: 20px;
      font-weight: 600;
      background-color: rgba(64, 160, 255, 0.383);
      // border-radius: 35px;
    }

    ::v-deep
      .tabs2
      .el-tabs__nav-scroll
      .el-tabs__nav
      .el-tabs__item.is-active {
      color: #3184d7;
      font-size: 18px;
      font-weight: 600;
      background-color: rgba(64, 160, 255, 0.383);
    }

    .childMenuBg {
      width: 100%;
      height: 3px;
      background: linear-gradient(to left, #3030301b, #0286f9, #3030301b);
      margin: 8px 10px 0px 10px;
    }
  }

  .el-main {
    height: calc(100vh - 90px);
    // height: 100vh;
    margin: 0px;
    padding: 0px;
  }

  ::v-deep .el-drawer.rtl {
    background-color: rgb(0, 15, 52) !important;
  }

  ::v-deep .dv-border-box-7 {
    box-shadow: none !important;
  }
}
</style>
<style lang="scss">
.myClass .el-dialog__header {
  background-color: rgba(0, 15, 52) !important;
  padding: 5px 20px 5px !important;

  .el-dialog__headerbtn {
    top: 0px;
    right: 0px;
  }

  .el-dialog__title {
    color: #0a74ff96 !important;
    font-weight: 600;
  }
}

.myClass .el-dialog__body {
  background-color: rgba(0, 15, 52);
  padding: 5px 20px;
}

.rotate {
  display: block;
  animation: rotate 0.5s linear infinite;
  color: red;
}

@keyframes rotate {
  0% {
    transform: rotateZ(0deg);
    /*从0度开始*/
    opacity: 1;
  }

  25% {
    transform: rotateZ(20deg);
  }

  50% {
    transform: rotateZ(0deg);
    opacity: 0.5;
  }

  75% {
    transform: rotateZ(-20deg);
  }

  100% {
    transform: rotateZ(0deg);
    opacity: 0;
  }
}
</style>
